// content.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === "getHtmlContent") {
    // 向 background.js 请求获取文件内容
    chrome.runtime.sendMessage(
      { action: "fetchHtmlContent" },
      function (response) {
        sendResponse({ htmlContent: response.htmlContent });
      }
    );

    // 保持消息通道打开，直到异步操作完成
    return true;
  }
  if (request.action === "appendElement" && request.htmlContent) {
    // 在当前页面追加元素
    var newElement = document.createElement("div");
    newElement.innerHTML = request.htmlContent;
    document.body.appendChild(newElement);
    // chrome.runtime.sendMessage({ action: "fetchJS",  scriptElementSrc:scriptElement.src}, function (response) {
    //   // sendResponse({ jsContent: response.jsContent });
    //   console.log(response)
    //   if (response.jsContent) {
    //     // var scriptCode = scriptElement.textContent || scriptElement.innerText;
    //     var scriptNode = document.createElement("script");
    //     scriptNode.textContent = response.jsContent;
    //     document.body.appendChild(scriptNode);
    //   }
    // });

    // 如果需要执行脚本，你可以选择手动执行
    var scriptElements = newElement.querySelectorAll("script");
    for (let index = 0; index < scriptElements.length; index++) {
      const scriptElement = scriptElements[index];
      if (scriptElement.src) {
        var eleScript = document.createElement("script");
        eleScript.type = "text/javascript";
        eleScript.src = scriptElement.src;
        document.body.appendChild(eleScript);
      }
      else if(scriptElement.textContent || scriptElement.innerText){
        var scriptCode = scriptElement.textContent || scriptElement.innerText;
        var scriptNode = document.createElement("script");
        scriptNode.textContent = scriptCode;
        document.body.appendChild(scriptNode);
      }
    }
  }
  if (request.action === "appendJS" && request.htmlContent) {
    // 在当前页面追加元素
    // 如果需要执行脚本，你可以选择手动执行
  }
});
